package com.liam.lotterysystem.service.activitystatus.impl;

import com.liam.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.liam.lotterysystem.common.exception.ServiceException;
import com.liam.lotterysystem.service.ActivityService;
import com.liam.lotterysystem.service.activitystatus.ActivityStatusManager;
import com.liam.lotterysystem.service.activitystatus.operator.AbstractActivityOperator;
import com.liam.lotterysystem.service.dto.ConvertActivityStatusDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: LiamLMK
 * @CreateTime: 2024-11-04
 * @Description: 责任链体现
 * @Version: 1.0
 */

@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class ActivityStatusManagerImpl implements ActivityStatusManager {

    @Autowired
    private final Map<String, AbstractActivityOperator> operatorMap = new HashMap<>();
    @Autowired
    private ActivityService activityService;

    @Override
    public void handlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // 1. 活动状态扭转有依赖性（与其他状态有关）
        // 2. 状态扭转条件可能会扩展，当前写法扩展性差，维护性差

        if (CollectionUtils.isEmpty(operatorMap)) {
            log.warn("operatorMap 为空");
            return;
        }

        Map<String, AbstractActivityOperator> currMap = new HashMap<>(operatorMap);
        boolean update = false;
        // 先处理：人员、奖品
        update = processConvertStatus(convertActivityStatusDTO, currMap, 1);

        // 后处理：活动
        update = processConvertStatus(convertActivityStatusDTO, currMap, 2) || update; // 有一个是true就返回true

        // 更新缓存
        if (update) {
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }
    }

    @Override
    public void rollBackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // operatorMap：活动、奖品、人员
        // 活动是否需要回滚 —— 绝对需要，
        // 原因：奖品均恢复成INIT，那么这个活动下的奖品绝对没抽完
        for (AbstractActivityOperator operator : operatorMap.values()) {
            operator.convert(convertActivityStatusDTO);
        }

        // 缓存更新
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }

    /**
     * 扭转状态
     *
     * @param convertActivityStatusDTO
     * @param currMap
     * @param sequence
     * @return
     */
    private Boolean processConvertStatus(ConvertActivityStatusDTO convertActivityStatusDTO,
                                         Map<String, AbstractActivityOperator> currMap,
                                         int sequence) {
        boolean update = false;

        // 遍历currMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> iterator = currMap.entrySet().iterator();
        while (iterator.hasNext()) {
            AbstractActivityOperator operator = iterator.next().getValue();
            // Operator是否需要转换：
            if (operator.sequence() != sequence || !operator.needConvert(convertActivityStatusDTO)) {
                continue;
            }
            // 需要转换：转换
            if (!operator.convert(convertActivityStatusDTO)) {
                log.info("{}状态转换失败,", iterator.next().getKey());
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_STATUS_CONVERT_ERROR);
            }
        }

        // currMap 删除当前Operator
        iterator.remove();
        update = true;
        // 返回
        return update;
    }
}
